package pkg.andru.service;

import java.util.ArrayList;
import java.util.List;

import pkg.andru.service.DownloadEvent.DownloadEventListener;
import pkg.andru.service.DownloadEvent.ErrorStatus;
import android.os.Handler;
import android.os.Looper;

public class DownloadEventWatcher {

    private static DownloadEventWatcher mWatcher;

    public static DownloadEventWatcher getInstance() {
        if (mWatcher == null) {
            mWatcher = new DownloadEventWatcher();
        }
        return mWatcher;
    }

    private List<DownloadEventListener> mListeners;
    private Handler mHandler;

    private DownloadEventWatcher() {
        mListeners = new ArrayList<DownloadEventListener>();
        mListeners.clear();
        mHandler = new Handler(Looper.getMainLooper());
    }

    public void registerDownloadEventListener(DownloadEventListener listener) {
        synchronized (mListeners) {
            if (mListeners.contains(listener)) {
                mListeners.remove(listener);
            }
            mListeners.add(listener);
        }
    }

    public void unRegisterDownloadEventListener(DownloadEventListener listener) {
        synchronized (mListeners) {
            mListeners.remove(mListeners);
        }
    }

    public void unRegisterAllDownloadEventListeners() {
        synchronized (mListeners) {
            mListeners.clear();
        }
    }

    void notifyDownloadEventListeners(final int eventId, final boolean right, final ErrorStatus status) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                synchronized (mListeners) {
                    for (DownloadEventListener listener : mListeners) {
                        listener.onDownloadEventCallback(eventId, right, status);
                    }
                }
            }
        });
    }

    void notifyDownloadEventAllFinished() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                synchronized (mListeners) {
                    for (DownloadEventListener listener : mListeners) {
                        listener.onAllDownloadFinished();
                    }
                }
            }
        });
    }

}
